/*
 *  StaticsUtility.cpp
 *  MarketDataAnalyzer 2
 *
 *  Created by jiro on 10/10/03.
 *  Copyright 2010 jiro music. All rights reserved.
 *
 */

#include "StaticsUtility.h"
#import <numeric>

double StaticsUtility::CalcMean( const InterpolatedData* data )
{
	double ret = 0;
	const int count = data->GetSampleCount();
	for ( int i = 0; i < count; i++ ) {
		ret += data->GetAt( i );
	}
	return ret / count;
}	

double StaticsUtility::CalcVariance( const InterpolatedData* data )
{
	double ret = 0;
	const double mean = CalcMean( data );
	const int count = data->GetSampleCount();
	for ( int i = 0; i < count; i++ ) {
		ret += pow( mean - data->GetAt( i ), 2 );
	}
	return ret / ( count - 1 );
}
	
double StaticsUtility::CalcStandardDeviation( const InterpolatedData* data )
{
	double variance = CalcVariance( data );
	return pow( variance, 0.5 );
}	

double StaticsUtility::CalcCovariance( const InterpolatedData* data0, const InterpolatedData* data1 )
{
	int sampleCount = data0->GetSampleCount() < data1->GetSampleCount() ? data0->GetSampleCount() : data1->GetSampleCount();
	const double mean0 = CalcMean( data0 );
	const double mean1 = CalcMean( data1 );
	double ret = 0.;
	for ( int i = 0; i < sampleCount; i++ ) {
		ret += ( data0->GetAt( i ) - mean0 ) * ( data1->GetAt( i ) - mean1 );
	}

	return ret / sampleCount;
}

double StaticsUtility::CalcCorelationCoefficient( const InterpolatedData* data0, const InterpolatedData* data1 )
{
	double stddev0 = CalcStandardDeviation( data0 );
	double stddev1 = CalcStandardDeviation( data1 );
	double covariance = CalcCovariance( data0, data1 );

	return covariance / ( stddev0 * stddev1 );
}